localforage.config({
  driver      : [localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE],
  name        : 'bmux',
  version     : 1.0,
  storeName   : 'sessions',
  description : 'browser session manager'
});

/*
// when chrome restores a session, check if the tabs match bmux saved sessions
// and if so, attach to the matching one
chrome.windows.onCreated.addListener(function() {
  chrome.tabs.query({"currentWindow": true}, function(tabs) {
    for (var i = 0; i < sessions.length; i++) {
      if (tabs == sessions) {
        sessions[i].active = true;
        break;
      }
    }
  });
});*/


/*
 *
 * update sessions when page updates
 *
 */
function updateCurrentSession(currentWindowId) {
  localforage.iterate(function(value, key, iteration) {
    value.windows.forEach(function(window) {
      if (window.id === currentWindowId) {
        // currently in session, update extension icon
        saveSession(key);
      }
    });
  });
}
chrome.tabs.onCreated.addListener(function(tab) {
  updateCurrentSession(tab.windowId);
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  updateCurrentSession(tab.windowId);
});
chrome.tabs.onMoved.addListener(function(tabId, moveInfo) {
  updateCurrentSession(moveInfo.windowId);
});
chrome.tabs.onActivated.addListener(function(activeInfo) {
  updateCurrentSession(activeInfo.windowId);
});
chrome.tabs.onDetached.addListener(function(tabId, detachInfo) {
  updateCurrentSession(detachInfo.oldWindowId);
});
chrome.tabs.onAttached.addListener(function(tabId, attachInfo) {
  updateCurrentSession(attachInfo.newWindowId);
});
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
  updateCurrentSession(removeInfo.windowId);
});

function getAllSessionWindows() {
    sessions = [];
    localforage.iterate(function(value, key, iteration) {
      session = value;
      session['name'] = key;
      sessions.push(session);
    }).then(function() {
      sessions.forEach(function(session) {
        session.windows.forEach(function(window) {
          chrome.windows.get(window.id, {populate: true}, function(window) {
            console.log(window);
            // do something
          });
        });
      });
    });
}
chrome.windows.onCreated.addListener(function(window) {
  updateCurrentSession(window.id);
});
chrome.windows.onRemoved.addListener(function(windowId) {
  updateCurrentSession(windowId);
});
chrome.windows.onFocusChanged.addListener(function(windowId) {
  updateCurrentSession(windowId);
});

var messenger = {
  sessionList: function(message) {
    chrome.runtime.sendMessage({sessionList: message});
  }
}

  function listSessions() {
    sessions = [];
    localforage.iterate(function(value, key, iteration) {
      session = value;
      session['name'] = key;
      sessions.push(session);
    }, function() {
      messenger.sessionList(sessions);
    });
  }

  function saveSession(sessionName, callback) {
    chrome.windows.getAll({populate: true}, function(windows) {
      var session = {};
      session['windows'] = windows;
      session['timeStamp'] = new Date().toString();
      session['name'] = sessionName;
      localforage.setItem(sessionName, session, function(err, value) {
        if (err) console.log(err);
        if (callback) callback();
      });
    })
  }

  function openSession(session) {
    session.windows.forEach(function(w) {
      chrome.windows.create({state: w.state, focused: w.focused}, function(window) {
        w.tabs.forEach(function(tab) {
          chrome.tabs.create({windowId: window.id, index: tab.index, url: tab.url, active: tab.active, pinned: tab.pinned});
        });
      });
    });
    saveSession(session.name);
  }

  function closeAllWindows() {
    chrome.windows.getAll(function(windows) {
      windows.forEach(function(window) {
        chrome.windows.remove(window.id)
      });
    });
  }

function closeWindow(windowId) {
  chrome.windows.remove(windowId);
}


/* 
 *
 * send data to UIs
 *
 */

chrome.runtime.onMessage.addListener(function(msg) {
  if (msg.request) {

    /*
     * send session data on UI start
     */
    if (msg.request[0] === "sessions") {
      listSessions();

    /*
     * create a new session
     */
    } else if (msg.request[0] === "createSession") {
      saveSession(msg.request[1], listSessions);

    /*
     * attach to session
     */
    } else if (msg.request[0] === "attach") {
      closeAllWindows();
      localforage.getItem(msg.request[1], function(err, value) {
        openSession(value);
      });
 
    /*
     * detach from session
     */
    } else if (msg.request[0] === 'detach') {
      closeAllWindows();
      chrome.windows.create();

    /*
     * rename a session
     * ~not functional~
     */
    } else if (msg.request[0] === 'rename') {
      localforage.getItem(msg.request[1], function(err, value) {
        localforage.removeItem(msg.request[1], function(err) {
          saveSession(msg.request[2], value);
        });
      });

    /*
     * remove a session
     */
    } else if (msg.request[0] === "removeSession") {
      localforage.removeItem(msg.request[1], function(err) {
        listSessions();
      });

    /*
     * clear sessions
     */
    } else if (msg.request[0] === "clearSessions") {
      localforage.clear().then(function() {
        listSessions();
      });

    }
  }
});

